<?php
require_once 'pages/TMSFrontPage.inc';

class TMSFrontContentPage extends TMSFrontPage {
/**
 * @var TCandyItem
 */	
	protected $pageItem;
	
	protected $currentCategory;
	
	protected function getPageItem($id){
		return $this->PagesModel->GetItem($id);
	}
	
	public function Handle(THttpRequest $request){
		if (isset($request->id))
			$this->pageItem = $this->getPageItem($this->getPageId($request->id));
		parent::Handle($request);
	}
	
	public function ContentItem(){
		if ($this->pageItem)
			return $this->pageItem;
		$this->service->RedirectToNotFound();	
	}
	
	public function IsParentItem(TMSFrontPageItem $item){
		if (parent::IsParentItem($item))
			return true;
		return $item->ItemId() == $this->ContentItem()->ItemId() && $item->ClassName() == $this->ContentItem()->ClassName();
	}
	
	
	public function Associations(IItem $type){
		return new TMSFrontPageItemIterator($this->pageItem->Associations($type), $this);
	}	
	
	protected function getCurrentCategory(){
		if (is_null($this->currentCategory)){
			$this->currentCategory = $this->getPageCategory($this->ContentItem()); 
			if (is_null($this->currentCategory) || $this->Service()->IsMenu($this->currentCategory->Slug))
				$this->currentCategory = false;
		}
		if ($this->currentCategory)
			return $this->currentCategory;
		return null;
	}
	
	public function SubItems(){
		if ($category = $this->getCurrentCategory()){
			$pi = new TMSFrontPageItem($category, $this);
			return $pi->Subs();
		}
		return new TArrayIterator(array());
	}
	
	public function SubCategories(){
		if ($category = $this->getCurrentCategory())
			return new TMSFrontPageItemIterator($this->CategoriesModel->GetContents($category->ItemId(),true,new TListOptions(array(new TFilterOption('IsPublished', TConditionType::C_EQUAL, true),new TFilterOption('Language', TConditionType::C_EQUAL, $this->Application()->Language)),array(new TSortingOption('OrderNumber')))),$this);
		return new TArrayIterator(array());
	}
		
	public function Keywords(){
		return $this->pageItem->Keywords;
	}
	
	public function Description(){
		return $this->pageItem->Description?$this->pageItem->Description:$this->pageItem->Snippet;
	}
	
	public function Title(){
		return $this->pageItem->Title;
	}
	
	public function Contents(){
		return $this->pageItem->PageContents;
	}
	
	public function Path(){	
		$result = array();
		if ($category = $this->getCurrentCategory())
			$this->getCategoryPath($category, $result);
		else 
			 $this->getNestedPagePath($this->pageItem, $result);
		return array_reverse($result);
	}
	
	protected function processUrlParameters(array $parameters){
		if (!isset($parameters['id']) && $this->pageItem)
			$parameters['id'] = $this->pageItem->ItemId();
		return $parameters;
	}	
	
}
